package com.lzq.rabbitmqdemo.advanced_features.listener;

import com.lzq.rabbitmqdemo.advanced_features.constant.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class RetryQueueListener {

    @RabbitListener(queues = Constants.RETRY_QUEUE)
    public void ListenerQueue(Message message) throws Exception {
        System.out.printf(" 接收到消息: %s, deliveryTag: %d%n", new String(message.getBody(),"UTF-8"),
                message.getMessageProperties().getDeliveryTag());
        //模拟处理失败
        try {
            int num = 3 / 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("处理完成");
    }


    @RabbitListener(queues = Constants.RETRY_QUEUE)
    public void ListenerQueue(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.printf(" 接收到消息: %s, deliveryTag: %d%n", new
                            String(message.getBody(), "UTF-8"),
                    message.getMessageProperties().getDeliveryTag());
            //模拟处理失败
            int num = 3 / 0;
            System.out.println(" 处理完成 ");
            //3. 手动签收
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            //4.异常了就拒绝签收
            Thread.sleep(1000);
            //第三个参数requeue,是否重新发送,如果为true,则会重新发送,若为false,则直接丢弃
            channel.basicNack(deliveryTag, true, true);
        }
    }
}
